package top.dotgo.kit.ds;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author jornl
 * @date 2020/2/5 23:32 星期三
 */
@Slf4j
public class DynamicDataSourceContextHolder {

    public static final String SYS_TAG = "SYS";
    public static final String BIZ_TAG = "SYS";
    /**
     * 线程独立
     */
    private static final ThreadLocal<String> CONTEXT_HOLDER = new ThreadLocal<>();

    private DynamicDataSourceContextHolder() {
    }

    /**
     * 获得数据源
     */
    public static synchronized String getDataSourceType() {
        if (StrUtil.isEmpty(CONTEXT_HOLDER.get())) {
            setDataSourceType(SYS_TAG);
        }
        return CONTEXT_HOLDER.get();
    }

    /**
     * 设置数据源
     */
    private static synchronized void setDataSourceType(String dbTag) {
        log.info("切换到{}数据源", dbTag);
        CONTEXT_HOLDER.set(dbTag);
    }

    /**
     * 设置 sys 系统库
     */
    public static synchronized void setSys() {
        setDataSourceType(SYS_TAG);
    }

    /**
     * 设置 biz 业务库
     *
     * @param dbTag dbTag 为空  则 BIZ_TAG
     */
    public static synchronized void setBiz(String dbTag) {
        if (StrUtil.isEmpty(dbTag)) {
            setDataSourceType(BIZ_TAG);
        } else {
            setDataSourceType(dbTag);
        }
    }

    /**
     * 清空数据源
     */
    public static void clearDataSourceType() {
        CONTEXT_HOLDER.remove();
    }
}
